<?php
namespace control;
/*
*物料明细类
*/

use JetBrains\PhpStorm\NoReturn;

class materialDetailClass extends adIndexClass
{
	private const page  = 'materialDetail';
	private const table = 'material';
	private const title = '物料明细';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'code'          => [
                        'name'  => "{l.materialDetail.home.code}",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'name' => [
                        'name'  => "{l.materialDetail.home.materialName}",
                        'width' => 150,
                    ],
                    'typeName'  => [
                        'name'  => "{l.materialDetail.home.type}",
                        'width' => 150,
                    ],
                    'model'  => [
                        'name'  => "{l.materialDetail.home.model}",
                        'width' => 150,
                    ],
                    'unit'  => [
                        'name'  => "{l.materialDetail.home.unit}",
                        'width' => 60,
                    ],
                    'unit_one'         => [
                        'name'  => "{l.materialDetail.home.unit_one}",
                        'width' => 80,
                    ],
                    'unit_two'          => [
                        'name'  => "{l.materialDetail.home.unit_two}",
                        'width' => 80,
                    ],
                    'unit_one_num'          => [
                        'name'  => "{l.materialDetail.home.unitOne}",
                        'width' => 100,
                    ],
                    'unit_two_num'          => [
                        'name'  => "{l.materialDetail.home.unitTwo}",
                        'width' => 100,
                    ],
                    'barcode'          => [
                        'name'  => '{l.materialDetail.home.barcode}',
                        'width' => 160,
                        'sort' => 1,
                    ],
                    'salePrice'          => [
                        'name'  => str_replace(['{{unit}}'], [static::$unit], lang('materialDetail.home.salePrice')),
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'buyPrice'          => [
                        'name'  => str_replace(['{{unit}}'], [static::$unit], lang('materialDetail.home.buyPrice')),
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('materialDetail.home.code') => text(array("name" => "code")),
                    L('materialDetail.home.typeId')   => materialClass::typeSelect(name:'typeId',title:'请选择'),
                    L('materialDetail.home.materialName') => text(array("name" => "materialName")),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/*列表-查询条件*/
	public function home()
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power(self::page, "print")) {
            $button .= "<span onclick=\"get_checked_box('" . self::page . "','printEdit','listForm')\" class='spanButton'>".L('materialDetail.home.printBarcode')."</span>\n";
        }
		//返回
		return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/*客户列表-查询结果*/
	public function homeSearch()
	{
		//like查询数组
		$like = array(
			"a.code"  => $this->post('code'),
			"a.name"  => $this->post('materialName'),//名称
			"a.typePath"  => $this->post('typeId'),
		);
		//全等查询数组
		$equal = array(
			'a.coid'   => self::$coid,
		);
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'a.time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		//获取查询结果
		$where                       = search(array("like" => $like, "=" => $equal));
		$page                        = $this->page(array(
		    "table" => self::table . " as a",
            'field' => "a.*",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
		$_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate     = array(
				"box" => array("name" => "listId", "value" => $array['id'] ?: $array['materialId']),
			);
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'unit_one_num':
                    case 'unit_two_num':
                        $row[] = self::lostZero($array[$key],'numPrecision');
                        break;
                    case 'salePrice':
                    case 'buyPrice':
                        $row[] = self::lostZero($array[$key],'pricePrecision');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}


	/********打印弹窗**************/
	public function printEdit(): bool|string
	{
        $printNum = L('materialDetail.home.printNum');
		$root    = root;
		$listArr = explode(',', $this->post('listId'));
		$content = '';
		foreach ($listArr as $id) {
			//材料信息
            $material = query(self::table, "id = '$id'");
			$barcode   = $material['barcode'];
			$parameter = urlencode($barcode);
			$content   .= <<<efo
                            <li>
                               <div class="qr-content">
                                     <img alt="" src='{$root}pay/wxpay/wxScanPng.php?url={$parameter}'>
                                     <div class="qr-content-barcode">{$barcode}</div>
                                     <div class="qr-content-bottom">{$material['name']},{$material['model']}</div>
                                     <input name='listId[]' type='hidden' value='$id'>
                               </div>
                               <input class="text qr-num" name='num[]' placeholder='{$printNum}'>
                           </li>
efo;
		}
		$print = L('materialDetail.home.print');
		$html = <<<efo
                <form name="printForm" target="_blank" method="post" action="{$root}control/adIndex.html?cla=materialDetail&fun=printPage">
                <div class="printEditPage">
                      <ul>
                           {$content}
                      </ul>
                </div>
                
                <div style='width: 100%;margin-top: 40px;text-align: center;'>
                    <input type='submit' class='button' value='{$print}' ">
                </div>
                </form>

efo;

		return $this->layer(array("title" => "打印", "height" => 650, "width" => 900, "html" => $html . $this->style(), "button" => false));
	}

	/**
	 * 样式
	 */
	public function style(): string
	{
		return <<<efo
<style>
.printEditPage{width: 100%;height: 500px;overflow: auto;}
.printEditPage>ul>li{float: left;margin: 5px;padding: 5px}
.qr-content{width: 240px;height: 180px;background-color: #F0F8FA;text-align: center;margin: 10px;padding: 10px;overflow: auto}
.qr-content img{width: 120px}
.qr-content-barcode{font-size: 15px;font-weight: bold;margin: 5px 0}
.qr-content-bottom{word-wrap:break-word;}
.qr-num{width: 250px;margin: 10px}
</style>
efo;
	}

	/**
	 * 打印
	 */
	public function printPage(): string
	{
		$idArr   = $this->post('listId');
		$numArr  = $this->post('num');
		$root    = root;
		$content = '';
		foreach ($idArr as $index => $id) {
			if ($numArr[$index] > 0) {
				//材料信息
                $material = query(self::table, "id = '$id'");
				$barcode   = $material['barcode'];
				$parameter = urlencode($barcode);
				for ($i = 1; $i <= $numArr[$index]; $i++) {
					$content .= <<<efo
                                <div class="qr-content">
                                     <img alt="" src='{$root}pay/wxpay/wxScanPng.php?url={$parameter}'>
                                     <div class="qr-content-barcode">{$barcode}</div>
                                     <div class="qr-content-bottom">{$material['name']},{$material['model']}</div>
                                </div>
efo;
				}
			}
		}

		$html = <<<eof
                    <div id="content-box" style="display: none">
                        <div data-op-type='new-page'></div>
                    <!--    <div data-op-type="pendants">&lt;!&ndash; 定义页面部件（页眉/页脚/书签/水印背景等） &ndash;&gt;-->
                    <!--        <div class='pendant-title'>实发工资表</div>-->
                    <!--    </div>-->
                       <div data-op-type='mix-box'>
                        <div class="nop-fill-box">
                        {$content}
                        </div>
                      </div>
                    </div>
                  
eof;
		$html .= $this->style();
		$html .= <<<efo
<style>
.qr-content{width: auto;height: auto;margin: 0;overflow: unset;background-color: white}
.qr-content img{width: 90px}
.qr-content-bottom{font-size: 12px}
</style>
efo;

		$print = new printClass();

		return $print->showPrint(html: $html, data: ['padding' => "0mm",'simplePageNum'=>false, 'pageSizeOption' => ['width' => '60mm', 'height' => '40mm']]);
	}


	/**
	 * 导出
	 */
	public function exportData()
	{
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') order by time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $materialType = materialClass::getTypePath($array['typeId']);
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '物料编码'=>$array['code'],
                            '物料名称'=>$array['name'],
                            '分类'=>$materialType,
                            '规格型号'=>$array['model'],
                            '主单位'=>$array['unit'],
                            '辅单位1'=>$array['unit_one'],
                            '辅单位2'=>$array['unit_two'],
                            '辅单位1换算'=>self::lostZero($array['unit_one_num'],'numPrecision'),
                            '辅单位2换算'=>self::lostZero($array['unit_two_num'],'numPrecision'),
                            '条码'=>$array['barcode'],
                            '销售单价'=> self::lostZero($array['salePrice'],'pricePrecision'),
                            '采购单价'=>self::lostZero($array['buyPrice'],'pricePrecision'),
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
			$text = str_replace(['{{staffName}}'], [$this->control['name']], L('materialDetail.home.log'));
			$this->logText(["type" => self::page, "text" => $text]);
			$this->excelOut($title, $data, L('materialDetail.home.fileName').".xlsx");
            exit(0);
        }
		header("Location:" . getenv("HTTP_REFERER"));
	}

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                ],
                [
                    'columnName'=>'分类',
                    'aliasName'=>'分类',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'主单位',
                    'aliasName'=>'主单位',
                ],
                [
                    'columnName'=>'辅单位1',
                    'aliasName'=>'辅单位1',
                ],
                [
                    'columnName'=>'辅单位2',
                    'aliasName'=>'辅单位2',
                ],
                [
                    'columnName'=>'辅单位1换算',
                    'aliasName'=>'辅单位1换算',
                ],
                [
                    'columnName'=>'辅单位2换算',
                    'aliasName'=>'辅单位2换算',
                ],
                [
                    'columnName'=>'条码',
                    'aliasName'=>'条码',
                ],
                [
                    'columnName'=>'销售单价',
                    'aliasName'=>'销售单价（元）',
                ],
                [
                    'columnName'=>'采购单价',
                    'aliasName'=>'采购单价（元）',
                ],
            ]
        };
    }
}
